package com.tanhua.app.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.UserApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.domain.db.User;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.UserInfoVo;
import com.tanhua.util.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service   // 这里使用service  注解
public class UserService {

    @Reference
    private UserApi userApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    public ResponseEntity findByPhone(String phone) {
        User user = userApi.findByPhone(phone);
        return ResponseEntity.ok(phone);
    }

    public ResponseEntity saveUser(User user) {
        Long userId = userApi.saveUser(user);
        return ResponseEntity.ok(user);
    }

    // 用户的登入注册
    public ResponseEntity loginVerification(String phone, String vCode) {
        //短信验证码
        String redisCode = stringRedisTemplate.opsForValue().get("SMS_CODE_" + phone);
        if (!StrUtil.equals(vCode, redisCode)) {
            return ResponseEntity.status(500).body(ErrorResult.loginError());   //返回验证码错误
        }
        //删除redis验证码
        stringRedisTemplate.delete("SMS_CODE_" + phone);
        //根据手机号查询
        User user = userApi.findByPhone(phone);
        // 用户标记
        Boolean isNew = false;
        //如果没有查询  注册
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setPassword(SecureUtil.md5("12345"));
            Long userId = userApi.saveUser(user);
            user.setId(userId);
            isNew = true;
            //注册环信
            huanXinTemplate.register(userId);

        }
        //将用户信息生成token  存储到redis中
        Map Claims = new HashMap();
        Claims.put("id", user.getId());
        Claims.put("phone", phone);
        String token = JwtUtil.createToken(Claims);

        //将user 对象转换成json
        String json = JSON.toJSONString(user);

        //用户认证信息存储1天
        stringRedisTemplate.opsForValue().set("TOKEN_" + token, json, Duration.ofDays(1));
        //返回结果
        Map result = new HashMap();
        result.put("token", token);
        result.put("isNew", isNew);
        return ResponseEntity.ok(result);
    }

    @Autowired
    private SmsTemplate smsTemplate;

    //发送短信验证码
    public ResponseEntity login(String phone) {
        //生成六位随机数
        String code = RandomUtil.randomNumbers(6);
        code = "123456"; //TODO     上线之前恢复短信发送功能
        //将验证码存入 redis 中
        stringRedisTemplate.opsForValue().set("SMS_CODE_" + phone, code, Duration.ofMinutes(5));
        return ResponseEntity.ok(null);
    }

    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private OssTemplate ossTemplate;

    //根据token 获取对象
    public User findUserByToken(String token) {
        String json = stringRedisTemplate.opsForValue().get("TOKEN_" + token);

        if (StrUtil.isEmpty(json)) {
            return null;
        }

        //转为java对象
        User user = JSON.parseObject(json, User.class);
        //续期
        stringRedisTemplate.opsForValue().set("TOKEN_" + token, json, Duration.ofDays(1));
        return user;
    }

    // 完善头像信息
    public ResponseEntity loginReginfoPic(MultipartFile headPhoto, String token) throws Exception {
        //根据token获取用户对象
        User user = findUserByToken(token);
        //人脸识别
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());

        if (!detect) {
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }

        //oss 文件上传
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(),headPhoto.getInputStream());
         //跟新userInfoz
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(url);//头像
        userInfo.setCoverPic(url); // 封面
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);


    }

    public ResponseEntity findUserInfoVo(Long userID) {
        //调用rpc 根据ID 查询
        UserInfo info = userInfoApi.fingByUserId(userID);
        //转为vo对象
        UserInfoVo vo = new UserInfoVo();
        //复制来源对象中的属性到目标对属性中
        BeanUtil.copyProperties(info, vo);
        if (info.getAge() != null) {
            vo.setAge(info.getAge().toString());
        }
        //System.out.println(vo);
        return ResponseEntity.ok(vo);
    }

    //完善个人信息
    public void logininfo(UserInfo userInfo, String token) {
        //根据token 获取对象
        User user = findUserByToken(token);
        //userinfo 指定用户id
        userInfo.setId(user.getId());
        //调用roc保存
        userInfoApi.save(userInfo);
    }

    public ResponseEntity updateUserInfo(UserInfo userInfo, String token) {
        //根据token 查询用户id
        User user=findUserByToken(token);
        //给userInfo 绑定用户id
        userInfo.setId(userInfo.getId());
        //更新userinfo
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }
}
